<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>采购清单列表</title>
	<meta name="decorator" content="default"/>
	<style type="text/css">
		.table td {
			vertical-align: middle;
		}
	</style>
	<script type="text/javascript">
		$(document).ready(function() {
			$("#listForm").validate({
				submitHandler: function(form){
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
		});
		function selectAll(){
			$("input[name='detailId']").each(function(){
				$(this).attr("checked", $("#select_all").is(':checked'));
			});
		}
		//查看采购清单对应订单详情信息
        function showOrderDetail(id, productName){
        	top.$.jBox.defaults.top="8%";
        	top.$.jBox.open("iframe:${ctx}/ivm/purchase/showOrderDetail?id="+id+"&type=2", productName+"—订单详情",$(top.document).width()-500,$(top.document).height()-100,{
				buttons:{"确定":true}, loaded:function(h){
					$(".jbox-content", top.document).css("overflow-y","hidden");
				}
			});
        }
        
        //检测商品编号
        function checkProductCode(){
        	if($("#code").val()==""){
				showJBoxMess("请输入商品编号或名称.","error");
				return;
			}
        	var obj = $("#code");
			if($(obj).val()!=""){
				//异步保存活动
				$.ajax({
					type: 'post',
					url: '${ctx}/ivm/inventory/checkProductCode',
					data: 'merchantId=${merchant.id}&code='+$(obj).val(),
					dataType: 'json',
					success: function(data){
						if(data.status==200){
							var product = data.result;
							var isExists = false;
				        	$("input[id='productCode']").each(function(){
				        		if($(this).val()==product.code){
				        			showJBoxMess("商品"+$(obj).val()+"已存在，请重新输入！","error");
				        			isExists=true;
				        			return false;
				        		}
				        	});
				        	if(isExists) return;
							createHmPurchase();
						}else{
							showJBoxMess(data.message,"error");
						}
					},
					failure: function(){
						showJBoxMess("操作失败","error");
					}				
				});
			}
		}
		function createPurchase(){
			if($("input[name='detailId']:checked").length==0){
				showJBoxMess("请选择要操作的清单.","error");
				return;
			}
			if($("#memberId").val()==""){
				showJBoxMess("请选择采购员.","error");
				return;
			}
			if($("#purchaseSupplierId").val()==""){
				showJBoxMess("请选择采购供应商.","error");
				return;
			}
			var detailList = "";
			var isOK = true;
			$("input[name='detailId']:checked").each(function(index){
				var detailTr = $(this).parent().parent();
				var type = detailTr.find("input[name='type']").val();
				var orderId = detailTr.find("input[name='orderId']").val();
				var productId = detailTr.find("input[name='productId']").val();
				var purchaseNumber = detailTr.find("input[name='purchaseNumber']").val();
				var item = type+":"+orderId+":"+productId+":"+purchaseNumber;
				if(purchaseNumber=="0"){
					showJBoxMess("采购数量不能为0","error");
					isOK = false;
					return false;
				}
				detailList+=","+item;
			});
			if(!isOK) return;
			if(detailList!="") detailList = detailList.substring(1);
			//开始生成采购指令
			loading("正在提交，请稍等...");
			var param = "memberId="+$("#memberId").val()+"&supplierId="+$("#purchaseSupplierId").val()+"&detailList="+detailList;
			$.ajax({
				type: 'post',
				url: '${ctx}/ivm/purchase/createPurchase',
				data: param,
				dataType: 'json',
				success: function(data){
					if(data.status==200){
						showJBoxMess(data.message.split(":")[0],"success");
						$("#inputForm").submit();
					}else{
						showJBoxMess(data.message,"error");
					}
				},
				failure: function(){
					showJBoxMess("操作失败","error");
				}
			});
		}
		function createHmPurchase(){
			//异步手动生成商品采购清单
			$.ajax({
				type: 'get',
				url: '${ctx}/ivm/purchase/createHmPurchase',
				data: 'merchantId=${merchant.id}&code='+$("#code").val(),
				dataType: 'json',
				success: function(data){
					if(data.status==200){
						var num = $(".detail").length;
						var purchaseDetail = data.result;
						var html = '<tr class="detail">';
						html += '<td style="text-align: center;">';
						html += '<input type="hidden" id="type" name="type" value="2" />';
						html += '<input type="hidden" id="orderId" name="orderId" value="" />';
						html += '<input type="hidden" id="productId" name="productId" value="'+purchaseDetail.product.id+'" />';
						html += '<input type="hidden" id="productCode" value="'+purchaseDetail.product.code+'" />';
						html += '<input type="checkbox" id="detailId" name="detailId" value="'+num+'" />';
						html += '</td>';
						html += '<td>'+purchaseDetail.product.code+'</td>';
						html += '<td>'+purchaseDetail.product.name+'</td>';
						html += '<td>'+purchaseDetail.product.assisTitle+'</td>';
						html += '<td>'+purchaseDetail.product.stock+purchaseDetail.product.specUnit.name+'</td>';
						html += '<td>'+purchaseDetail.product.defaultSupplier.name+'</td>';
						html += '<td style="text-align: right;">';
						html += '<input name="purchaseNumber" value="'+purchaseDetail.purchaseNumber+'" htmlEscape="false" maxlength="20" class="required digits" onchange="updateNum(this, 0)" style="text-align: center; width: 80px; height: 100%; padding: 0px; margin:0px;"/>'+purchaseDetail.product.specUnit.name;
						html += '</td>';
						html += '<td>';
						html += '<a href="javascript:" onclick="removeDetail(this)">删除</a>';
						html += '</td>';
						html += '</tr>';
						$(".detailBody").append(html);
						$("#code").val("");
					}else{
						showJBoxMess(data.message,"error");
					}
				},
				failure: function(){
					showJBoxMess("操作失败","error");
				}				
			});
		}
		//查看订单绑定的采购清单信息
        function showPurchaseDetail(id){
        	top.$.jBox.defaults.top="8%";
        	top.$.jBox.open("iframe:${ctx}/ivm/purchase/showPurchaseDetail?id="+id, "采购指令明细",$(top.document).width()-500,$(top.document).height()-100,{
				buttons:{"确定":true}, loaded:function(h){
					$(".jbox-content", top.document).css("overflow-y","hidden");
				}
			});
        }
        //删除手动添加的商品
      	function removeDetail(obj){
      		top.$.jBox.confirm("确认删除该清单？",'系统提示',function(v,h,f){
				if(v=='ok'){
					$(obj).parent().parent().remove();
				}
			},{buttonsFocus:1});
			top.$('.jbox-body .jbox-icon').css('top','55px');
      	}
	</script>
</head>
<body>
<form:form id="inputForm" action="${ctx}/ivm/purchase/showPurchaseOrder" method="post">
	<tags:message content="${message}"/>
	<input type="hidden" id="orderIds" name="orderIds" value="${orderIds }" />
	<div style="margin:10px;">
		<div class="breadcrumb form-search">
			<label>供应商：</label>
			<select id="supplierId" name="supplierId" style="width: 150px;">
				<option value="">请选择</option>
				<c:forEach items="${supplierList}" var="supplier">
				<option value="${supplier.id }" <c:if test="${supplierId==supplier.id }">selected</c:if>>${supplier.name }</option>
				</c:forEach>
			</select>
			<label>采购指令状态：</label>
			<select id="purchaseState" name="purchaseState" class="input-small">
				<option value="0">请选择</option>
				<option value="1" <c:if test="${purchaseState==1 }">selected</c:if>>已生成</option>
				<option value="2" <c:if test="${purchaseState==2 }">selected</c:if>>未生成</option>
			</select>
			&nbsp;<input id="btnSubmit" class="btn btn-primary" type="submit" value="查询"/>
		</div>
		<table id="contentTable" class="table table-bordered table-condensed">
			<thead>
				<tr>
					<th><input type="checkbox" id="select_all" name="select_all" value="全选" onclick="selectAll();"/>全选</th>
					<th>商品编号</th>
					<th>商品名称</th>
					<th>商品规格</th>
					<th>库存数量</th>
					<th>默认供应商</th>
					<th width="100">采购数量</th>
					<th>采购指令</th>
				</tr>
			</thead>
			<tbody class="detailBody">
			<c:forEach items="${detailList}" var="detail" varStatus="vs">
				<tr class="detail">
					<td style="text-align: center;">
						<input type="hidden" id="type" name="type" value="1" />
						<input type="hidden" id="orderId" name="orderId" value="${detail.order.id }" />
						<input type="hidden" id="productId" name="productId" value="${detail.product.id }" />
						<input type="hidden" id="productCode" value="${detail.product.code }" />
						<c:if test="${detail.purchase==null}">	
						<input type="checkbox" id="detailId" name="detailId" value="${vs.index }" />
						</c:if>
					</td>
					<td>${detail.product.code }</td>
					<td>${detail.product.name }</td>
					<td>${detail.product.assisTitle }</td>
					<td>${detail.product.stock }${detail.product.specUnit.name }</td>
					<td>${detail.product.defaultSupplier.name }</td>
					<td style="text-align: right;">
						<c:if test="${detail.purchase==null}">	
						<input name="purchaseNumber" value="${detail.purchaseNumber<0?0:detail.purchaseNumber }" htmlEscape="false" maxlength="20" class="required digits" onchange="updateNum(this, 0)" style="text-align: center; width: 80px; height: 100%; padding: 0px; margin:0px;"/>${detail.product.specUnit.name }
						</c:if>
						<c:if test="${detail.purchase!=null}">	
						${detail.purchaseNumber }${detail.product.specUnit.name }
						</c:if>
					</td>
					<!-- <td>${detail.purchase==null?(detail.purchaseNumber==0?"有货":"库存不足"):"采购中" }</td> -->
					<td>
						<c:if test="${detail.purchase!=null}">
						<a href="#" onclick="showPurchaseDetail('${detail.purchase.id}')">${detail.purchase.code }</a>
						</c:if>
					</td>
				</tr>
			</c:forEach>
			</tbody>
		</table>
		<div align="right">
			<input type="text" id="code" name="code" htmlEscape="false" maxlength="200" class="required input-small" style="margin-bottom: 0px; width: 180px;" placeholder="请输入商品编号或名称"/>
			<input class="btn btn-primary" type="button" onclick="checkProductCode()" value="添加商品采购"/>
		</div>
		<!-- 派送员信息 -->
		<ul class="wl-tab-nav">
			<li><span>分配采购员</span></li>
		</ul>
		<div class="delivery_info">
			<label>采购员:</label>
			<select id="memberId" class="required input-small">
				<option value="">请选择</option>
				<c:forEach  items="${fns:getDeliveryMemberList(2)}" var="item">
					<option value="${item.id }">${item.name }</option>
				</c:forEach>
			</select>
			<label>采购供应商：</label>
			<select id="purchaseSupplierId" class="required" style="width: 150px;">
				<option value="">请选择</option>
				<c:forEach items="${supplierList}" var="supplier">
				<option value="${supplier.id }">${supplier.name }</option>
				</c:forEach>
			</select>
			<input class="btn btn-primary" type="button" onclick="createPurchase()" value="生成采购指令"/>
		</div>
	</div>
</form:form>
</body>
</html>